import React, { Component,Fragment } from 'react'
import { authRoutes } from 'routes'
import { Switch, Redirect, Route } from 'react-router-dom'
import MyLayout from 'components/MyLayout'
import {connect} from 'react-redux'
import NotFound from 'pages/NotFound'

class Admin extends Component {
  render() {
    return (
      <Fragment>
        <MyLayout>
          <Switch>
            {
              // 判断登录权限
              authRoutes.map(route => {
                return (
                  <Route 
                  key = {route.path}
                  path = {route.path}
                  render = {(routeProps)=>{
                    // 判断是否登录
                      if(this.props.token){
                        // 判断角色权限
                        if (route.meta.roles === '*' || route.meta.roles.some(role => role === this.props.role)){
                          // 说明具有权限
                          return <route.component {...routeProps}/>
                        }else{
                          return <Redirect to = '/admin/noPermission'/>
                        }
                      }else{
                        this.props.history.push({
                          pathname:'/login',
                          state:{
                            from: route.path
                          }
                        })
                      }
                  }}
                  />
                )
              })
            }
            <Route to = '/admin/404' component={NotFound} />
            <Redirect to = '/admin/dashBoard' from = '/admin' exact />
            <Redirect to = '/admin/404' />
          </Switch>
        </MyLayout>
      </Fragment>
    )
  }
}

const mapStateToProps = (state) => {
   return {
     token: state.user.token,
     role: state.user.userInfo.role
   }
}

export default connect(mapStateToProps)(Admin)